// pages/nearby/nearby.js
const app = getApp()
let request = require("../../utils/request.js");
let config = require('../../config/config.js')
var QQMapWx = require('../../utils/qqmap-wx-jssdk.js');
var qqmapsdk = new QQMapWx({ key: config.map_key })
let flag = true
Page({

  /**
   * 页面的初始数据
   */
  data: {
    statusBarHeight: app.globalData.statusBarHeight,
    screenHeight: 0,
    longitude: 0,
    latitude: 0,
    parkList: [],
    page: 1,
    pageSize: 10,
    isCanNext: true,
    canIUseGetUserProfile: false,
    nearbyBarIndex: 0,
    bannerList: [],
    ticketList: [],
    productList: [],
    merchantList: [],
    token: wx.getStorageSync('token'),
    parkTicket: -1,
    monthCard: -1,
    value: '',
    showSearchList:true,
    search:''  //搜索内容
  },
  TimeID: -1,  

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log('参数:', options)
    if (wx.getUserProfile) {
      this.setData({ canIUseGetUserProfile: true })
    }
    // 获取屏幕高度
    this.setData({
      screenHeight: wx.getSystemInfoSync().screenHeight,
      token: wx.getStorageSync('token'),
      parkTicket: options.parkTicket,
      reserve: options.reserve,
      monthCard: options.monthCard,
    })
    //  获取当前位置
    this.getUserLocation()
  },
    /**
   * 授权登录
   */
  bindGetUserInfo: function (e) {
    console.log('授权登录')
    let that = this;
    // let url = e.currentTarget.dataset.url
    let userInfo = e.detail.userInfo;
    wx.setStorageSync('userInfo', userInfo)
    if (userInfo) {
      this.setData({
        userInfo: userInfo
      })
      wx.login({
        success: res => {
          that.getToken(res.code);
        }
      });
    }
  },
  // 点击搜索隐藏列表
  hiddenlist() {
    let searchContent = []
    this.setData({
      showSearchList:false,
      searchList: searchContent
    })
  },
  // 搜索内容
  onChangeSearch(e) {   
    let parkName = e.detail;
    let searchName = parkName.replace(/\s+/g, '')
    clearTimeout(this.TimeID);  //设置定时器  防抖
    this.TimeID = setTimeout(()=> {
      if( searchName ) {
        let url = '/park/info/getNearMonthCardParkList';
        let longitude = this.data.longitude;
        let latitude = this.data.latitude;
        request.http(
          url,
          'GET',
          {  parkName: searchName,longitude ,latitude }
        ).then( res=>{
          console.log(res.data.data.records);
          let searchList = res.data.data.records;
              for ( var i = 0; i<searchList.length; i++ ) {
              // console.log(searchList[i].parkImgUrl);
              if (searchList[i].parkImgUrl == '') {
                searchList[i].parkImgUrl = 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.zcool.cn%2Fcommunity%2F017bcb58b4db5fa801219c7719b5ff.jpg%401280w_1l_2o_100sh.jpg&refer=http%3A%2F%2Fimg.zcool.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1631772791&t=f97c88d0443ed9fe68c2ee2a27ee5096';
              }
            }
          this.setData({
            searchList,
            showSearchList:false
          })
        })
      }
    }, 1000);
    
  },
  // 搜索的取消按钮触发
  onCancel() {
    this.setData({
      showSearchList: true
    })
  },

  /**
   * 顶部导航栏按钮
   */
  selectNearbyBar(e) {
    let index = e.currentTarget.dataset.index
    if (index == this.data.nearbyBarIndex) {
      return
    }
    this.setData({
      nearbyBarIndex: index
    })
  },
  /**
   * swiper组件滑动切换事件
   */
  changeNearbyBar(e) {
    let index = e.detail.current
    this.setData({
      nearbyBarIndex: index
    })
  },
  /**
   * 获取用户当前位置
   */
  getUserLocation() {
    let that = this;
    wx.getLocation({
      type: 'gcj02',
      success(res) {
        console.log(res);
        let longitude = res.longitude;
        let latitude = res.latitude;
        that.setData({
          longitude: res.longitude,
          latitude: res.latitude
        });
        //  获取附近停车场
        that.getParks(longitude, latitude);
      }
    })
  },
  /**
   * 领取优惠券
   */
  getCoupon(e) {
    let index = e.currentTarget.dataset.index
    let ticketList = this.data.ticketList
    request.http('/customer/ticket/receive-ticket', 'POST', { ticketId: ticketList[index].id })
      .then(res => {
        let data = res.data
        if (data.code == 200) {
          wx.showToast({
            title: '领取成功',
          })
        }
      })
  },
  /**
  * 计算两点之间距离
  * @param {Object} from 起始位置经纬度
  * @param {Array} to 终点位置经纬度
  * @param {Function} callback 回调函数
  */
  calculateDistance(from, to, callback) {
    qqmapsdk.calculateDistance({
      mode: 'driving',
      from,
      to,
      success(res) {
        callback(res)
      },
      fail: function (error) {
        console.error(error);
      },
    })
  },
  /**
   * 在地图中打开
   */
  toMap(e) {
    let index = e.currentTarget.dataset.index
    let merchantList = this.data.merchantList
    wx.openLocation({
      latitude: merchantList[index].latitude * 1,
      longitude: merchantList[index].longitude * 1,
      name: merchantList[index].shopName,
      address: merchantList[index].shopAddress,
    })
  },
  /**
 * 获取用户信息
 */
  getUserProfile(e) {
    let that = this;
    let index = e.currentTarget.dataset.index
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认
    // 开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    wx.getUserProfile({
      desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        that.setData({
          userInfo: res.userInfo
        })
        wx.setStorageSync('userInfo', res.userInfo)
        wx.login({
          success: res => {
            that.getToken(res.code, index);
          }
        });
      }
    })
  },
  /**
   * 获取Token
   * @param {String} code 微信返回的用户code
   * @param {Number} index 当前专属停车按钮索引
   */
  getToken(code) {
    let that = this
    let info = this.data.userInfo;
    let url = '/customer/info/authorize'
    let params = {
      avatar: info.avatarUrl,
      code: code,
      nickname: info.nickName,
      sex: info.gender == 0 ? 'UNKNOWN' : info.gender == 1 ? 'MEN' : 'WOMEN',
    }
    request.http(url, 'POST', params)
      .then(res => {
        var data = res.data
        if (data.code == 200) {
          let token = data.data.token
          // let parkData = this.data.parkList[index]
          wx.setStorageSync('token', token)
          wx.setStorageSync('customerId', data.data.customerId)
          that.setData({ token: token })
          //判断是不是新用户，新用户授权后跳转 绑定车牌页面
            if(data.data.isNew == 1){
              wx.navigateTo({ url: '../licencePlate/licencePlate' }) 
            }
          // wx.navigateTo({
          //   url: '../vipCharge/vipCharge?parkData=' + JSON.stringify(parkData) + '&index=1',
          // })
        }
      })
  },
  /**
   * 触底加载
   */
  scrollTolower() {
    if (!flag) {
      return
    }
    flag = false
    this.setData({ page: this.data.page + 1 })
    this.getParks(this.data.longitude, this.data.latitude)
  },
  /**
   * 获取附近停车场
   * @param {Number} longitude 经度
   * @param {Number} latitude 纬度
   */
  getParks(longitude, latitude) {
    if (!this.data.isCanNext) {
      return
    }
    let that = this;
    let params = {
      longitude: longitude,
      latitude: latitude,
      currentPage: that.data.page,
      pageSize: that.data.pageSize,
      parkTicket: this.data.parkTicket == 1 ? 1 : -1,
      reserve: this.data.reserve == 1 ? 1 : -1,
      monthCard: this.data.monthCard == 1 ? 1 : -1
    }
    request.http(
      '/park/info/getNearMonthCardParkList', 'GET', params
    ).then((res) => {
      console.log('附近的停车场',res);
      if (res.data.code == 200) {
        let parkLists = that.data.parkList
        let parkList = res.data.data.records;
        let parkNearby = []
        if (parkList.length <= 0) {
          that.setData({ isCanNext: false })
        }
        for (var i = 0; i < parkList.length; i++) {
          parkNearby.push({ longitude: parkList[i].longitude, latitude: parkList[i].latitude, })
        }
        that.calculateDistance(
          { longitude: longitude, latitude: latitude, },
          parkNearby,
          function (res) {
            let data = res
            // console.log( res );
            if (data.status == 0) {
              for (var i = 0; i < parkList.length; i++) {
                let distance = data.result.elements[i].distance;
                parkList[i].distances = (distance / 1000).toFixed(2)
                if(parkList[i].parkImgUrl){
                  let index = parkList[i].parkImgUrl.split(',')[0].lastIndexOf(".")
                  let name = parkList[i].parkImgUrl.split(',')[0].substr(0, index)
                  let ext = parkList[i].parkImgUrl.split(',')[0].substr(index+1)
                  parkList[i].parkImgUrl = name + '@_@350.' + ext
                }else{
                  parkList[i].parkImgUrl = 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.zcool.cn%2Fcommunity%2F017bcb58b4db5fa801219c7719b5ff.jpg%401280w_1l_2o_100sh.jpg&refer=http%3A%2F%2Fimg.zcool.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1631772791&t=f97c88d0443ed9fe68c2ee2a27ee5096';
                }
              }
              parkLists = parkLists.concat(parkList)
              that.setData({ parkList: parkLists })
            }
          }
        )
        flag = true
      }
    })
  },
  /**
     * 跳转到领取码币页面
     */
    toReceiveMabi(){
      wx.showToast({ title: '开发中', icon: 'none' })
    },

    
  /**
   * 跳转到会员中心
   */
  toVip(e) {
    let parkData = e.currentTarget.dataset.park;
    // let data = {
    //   id : e.currentTarget.dataset.park.id,
    //   type: e.currentTarget.dataset.park.type,
    //   distances: e.currentTarget.dataset.park.distances,
    // }
    if(this.data.token){
      wx.navigateTo({ url: '/pages/pay/monthly/monthly?parkData=' + encodeURIComponent(JSON.stringify(parkData)) })
    } else {
      //  获取用户信息
      this.getUserProfile('/pages/pay/monthly/monthly?parkData=' + encodeURIComponent(JSON.stringify(parkData)))
    }


  },
  // 跳转到白天卡页面
  todayCard(e) {
    let parkData = e.currentTarget.dataset.park;
    // let data = {
    //   id : e.currentTarget.dataset.park.id,
    //   type: e.currentTarget.dataset.park.type,
    //   distances: e.currentTarget.dataset.park.distances,
    // }
    if(this.data.token){
      wx.navigateTo({ url: '/pages/dayCard/dayCard?parkData=' + encodeURIComponent(JSON.stringify(parkData)) })
    } else {
      //  获取用户信息
      this.getUserProfile('/pages/dayCard/dayCard?parkData=' + encodeURIComponent(JSON.stringify(parkData)))
    }
  },


  // 跳转夜间卡页面
  toRightCard(e) {
    let parkData = e.currentTarget.dataset.park;
    // let data = {
    //   id : e.currentTarget.dataset.park.id,
    //   type: e.currentTarget.dataset.park.type,
    //   distances: e.currentTarget.dataset.park.distances,
    // }
    if(this.data.token){
      wx.navigateTo({ url: '/pages/pay/nightCard/nightCard?parkData=' + encodeURIComponent(JSON.stringify(parkData)) })
    } else {
      //  获取用户信息
      this.getUserProfile('/pages/pay/nightCard/nightCard?parkData=' + encodeURIComponent(JSON.stringify(parkData)))
    }
  },
  /**
   * 在地图中打开
   */
  toMapNavigation(e) {
    console.log(e);
    let index = e.currentTarget.dataset.index
    let parkData = this.data.parkList[index]
    let latitude = Number(parkData.latitude)
    let longitude = Number(parkData.longitude)
    console.log(parkData);
    wx.openLocation({
      latitude,
      longitude,
      name: parkData.parkName,
      address: parkData.parkAddress,
      scale: 14
    })
  },

  /**
 * 计算两点之间距离
 * @param {Object} from 起始位置经纬度
 * @param {Array} to 终点位置经纬度
 * @param {Function} callback 回调函数
 */
  calculateDistance(from, to, callback) {
    if (to.length <= 0) {
      return
    }
    qqmapsdk.calculateDistance({
      mode: 'driving',
      from,
      to,
      success(res) {
        callback(res)
      },
      fail: function (error) {
        console.error(error);
      },
    })
  },
  /**
   * 跳转到预约页面
   */
  toReserve(e){
    console.log('跳转到预约页面：', e)

    if(e.currentTarget.dataset.park.reserveParkSpace == 0){
      wx.showToast({ title: '当前可预约车位为0，请选择其他停车场', icon: 'none' })
      return
    }
    
    if(this.data.token){
      wx.navigateTo({ url: '/pages/subscribe/subscribe?parkId=' + e.currentTarget.dataset.park.id + '&parkName=' + e.currentTarget.dataset.park.parkName })
    } else {
      //  获取用户信息
      this.getUserProfile('/pages/subscribe/subscribe?parkId=' + e.currentTarget.dataset.park.id + '&parkName=' + e.currentTarget.dataset.park.parkName)
    }
  },
  /**
   * 跳转到领取停车券页面：
   */
  toReceiveTicket(e){
    console.log('跳转到领取停车券页面：', e)
    if(this.data.token) {
      wx.navigateTo({ url: '/pages/park-ticket/parkTicket?parkId=' + e.currentTarget.dataset.park.id })
    } else {
      //  获取用户信息
      this.getUserProfile('/pages/park-ticket/parkTicket?parkId=' + e.currentTarget.dataset.park.id)
    }
  },
    /**
   * 获取用户信息
   */
  getUserProfile(url) {
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认
    // 开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    wx.getUserProfile({
      desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        this.setData({ userInfo: res.userInfo })
        wx.setStorageSync('userInfo', res.userInfo)
        wx.login({
          success: res => {
            this.getToken(res.code, url);
          }
        });
      }
    })
  },
  /**
   * 获取Token
   * @param {String} code 微信返回的用户code
   */
  getToken(code, src) {
    let info = this.data.userInfo;
    let params = {
      avatar: info.avatarUrl,
      code: code,
      nickname: info.nickName,
      sex: info.gender == 0 ? 'UNKNOWN' : info.gender == 1 ? 'MEN' : 'WOMEN',
    }
    request.http(
      '/customer/info/authorize', 
      'POST', 
      params
    ).then(res => {
        var data = res.data
        if (data.code == 200) {
          let token = data.data.token
          wx.setStorageSync('token', token)
          wx.setStorageSync('customerId', data.data.customerId),
          this.setData({
            token,
            userInfo: wx.getStorageSync('userInfo'),
            websocketUrl: app.globalData.websocketUrl + data.data.customerId
          })

          //  授权后，跳转页面
          if (src) { wx.navigateTo({ url: src }) }
        } else {
          wx.removeStorageSync('userInfo')
        }
      })
  },
})